


import React, { FC, useEffect, useRef,useState } from 'react'
import { Button, Form, Input ,Toast} from 'antd-mobile'
import { Link, useSearchParams,useNavigate} from 'react-router-dom'
import { reg } from '../../utils/validate'
import { Http } from '../../api'
import { connect } from 'react-redux'
import { getuserInfoAsync } from '../../redux/actions'
const LoginByPhone: FC<any> = ({
  dispatch
}) => {
  const formRef: any = useRef()
  const [form] = Form.useForm()
  const [disabled,setDisabled] = useState<boolean>(true)
  const [searchParams] = useSearchParams()  // 获取query值
  let [count,setCount] = useState<number>(120)  //防抖
  const [toggle,setToggle] = useState<boolean>(true)  //开关
  let timer:any  = null;  //倒计时
  const router = useNavigate()  //跳转

  useEffect(()=>{
    const phone =searchParams.get('phone')  //获取里面phone的值
    if (phone) {
      form.setFieldsValue({'phone':phone})
      setDisabled(!reg.phone.test(phone))

    }else{
      form.setFieldsValue({'phone':localStorage.getItem('phone')})
      if(localStorage.getItem('phone')){
        setDisabled(!reg.phone.test(localStorage.getItem('phone')))
      }
    }

    return ()=>{
      clearInterval(timer)
      timer = null
    }
  },[])

    const checkPhone =(value:any)=>{
    console.log(value);
    setDisabled(!reg.phone.test(value))
  }

  const timeDown = ()=>{
    setCount(--count)
    setToggle(false)
    timer = setInterval(()=>{
      if(count>0){
        setCount(--count)
        setToggle(false)
      }else{
        clearInterval(timer)
        timer = null;
        setCount(120)
        setToggle(true)
      }
    },1000)
  }

  
  const startSendCaptcha = async ()=>{
    timeDown()

    let res:any  = await Http.sentcaptcha({
      phone:form.getFieldValue('phone')
    })

    if(res.code==200){
      Toast.show({
        icon:"success",
        content: res.msg,
      })
    }
  }

  // 验证码登录
  const formSubmit = ()=>{
    form.submit()
 }
 const onFinish = async (value:any) =>{
  console.log(value ) 
  let res:any = await Http.verifycaptcha(value)  //接口
  if(res.code==200){
    sessionStorage.setItem("token",res.token)  //存 token
    localStorage.setItem("phone",value.phone) 

      // 解决异步问题 当数据请求成功后，再向下执行后面的操作（同步）
    let data:any = await Http.getuserinfo({})
    if (data.code==200) {
      dispatch({
        type:"getuserInfoAsync",
        payload:data.result
      })
    }
    // 需要继续优化（成功）
    if (searchParams.get('from')) {
      // good
      // 只有加from 跳个人中心，其他全部上一级
      router('/main/mine')
    }else{
      router(-1)  //回退上一级
    }


  //   dispatch(getuserInfoAsync())  //登录成功 获取 用户信息
  // if (searchParams.get('from')) {
  //   // good
  //   router(-1)
  // }else{
  //   router('/main/mine')  //登录成功跳 mine 
  // }
  }
}

useEffect(()=>{
  console.log(form.getFieldsValue())
},[form.getFieldValue('phone')])


  return (
    <div>
      <Form 
       onFinish={onFinish}
      form ={form}
      ref={formRef}
      layout='horizontal'
      mode='card'
        footer={
          <div style={{width:'100%',display:'flex'}}>
            <Button style={{flex:1,margin:'0 10px'}} onClick={formSubmit} color='success' size='large'>
              验证码登录
            </Button>
            <Button
           style={{flex:1,margin:'0 10px'}}
              color='danger'
              onClick={() => {
                formRef.current.resetFields()
              }}
              size='large'
            >重置数据</Button>
            
          </div>
        }
      >
        <Form.Item label='手机号' name='phone'
          rules={[
            { required: true },
            {pattern:reg.phone,message:"请输入有效的手机号"}
          ]}
        >
          <Input placeholder='请输入用户名' clearable onChange={checkPhone} />
        </Form.Item>
        {/* <Form.Item label='短信验证码' name='captcha' disabled={disabled} extra={
        toggle?<a  onClick={startSendCaptcha}>发送</a>
      :<a>发送</a>}>
          <Input   style={{flex:1}} type="number"  placeholder='请输入验证码' />
        </Form.Item> */}
            <Form.Item label='验证码' name="captcha" extra={
          toggle?<Button color="warning" size='small'   onClick={startSendCaptcha} disabled={disabled} >发送</Button>
          :<Button color="default" size='small'   disabled={disabled} >{count} S</Button>
        }
        rules={[
          { required: true },
          { pattern:reg.code,message:"请输入有效的验证码"}
        ]}
        >
          <Input  style={{flex:1}} type="number"   placeholder='请输入验证码' />
        </Form.Item>

        <Form.Item>
          <div className="lines" style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <div className="item">
            <Link to="/register" style={{color:'pink'}}>去注册?</Link>
            </div>
            <div className="item">
            <Link to="/findpass" style={{color:'#f50'}}>找回密码?</Link>
            </div>
          </div>
        </Form.Item>
      </Form>
    </div>
  )
}

export default connect()(LoginByPhone)